/**
 * 	Controller.java
 *
 *  This file is part of the PDFGen Syllabus Formatter Project.
 *  Copyright (C) 2011
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.dlsu.pdfgen;

import java.awt.Desktop;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JOptionPane;

import org.dlsu.pdfgen.exceptions.InvalidXMLFileFormatException;
import org.dlsu.pdfgen.gui.ErrorFrame;
import org.dlsu.pdfgen.gui.MainWindow;
import org.dlsu.pdfgen.io.Revised2011XMLReader;
import org.dlsu.pdfgen.struct.Revised2011Syllabus;

import com.itextpdf.text.DocumentException;

/**
 * The controller class for the GUI.
 * 
 * @author Kevin See
 * 
 */
public class Controller {

	private MainWindow mainWindow;

	/**
	 * The constructor.
	 */
	public Controller() {
		System.out.println("Controller started.");
		mainWindow = new MainWindow(this);
	}

	public String generateTempPDF() {

		try {
			//String tDir = System.getProperty("java.io.tmpdir");
			String output = mainWindow.getFileName();
			
			// Conditional is the best way to compare empty string
			// in Java
			if("".equals(output)) {
				output = "preview";
				
				File src = new File(mainWindow.getSource());
				File dest = new File(output + ".pdf");

				Revised2011Formatter f = null;
				Revised2011Syllabus s = new Revised2011Syllabus();

				s = Revised2011XMLReader.getInstance().readSyllabus(src.getAbsolutePath());
				f = new Revised2011Formatter(s, dest.getAbsolutePath());

				dest.deleteOnExit();

				mainWindow.displaySuccess("Successfully created preview.");

				return dest.getAbsolutePath();
			}
			else {
				File src = new File(mainWindow.getSource());
				File dest = new File(output + ".pdf");

				Revised2011Formatter f = null;
				Revised2011Syllabus s = new Revised2011Syllabus();

				s = Revised2011XMLReader.getInstance().readSyllabus(src.getAbsolutePath());
				f = new Revised2011Formatter(s, dest.getAbsolutePath());

				dest.deleteOnExit();

				mainWindow.displaySuccess("Successfully created preview.");

				return dest.getAbsolutePath();
			}
			

		} catch (InvalidXMLFileFormatException e) {
			mainWindow.displayInvalidXML();
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			mainWindow.displayError();
			e.printStackTrace();
		} catch (DocumentException e) {
			mainWindow.displayError();
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			mainWindow.displayError();
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Generates the PDF using the source file, destination directory and the
	 * output file name (optional) from the GUI.
	 */
	public void generatePDF() {
		File src = new File(mainWindow.getSource());
		File dest = new File(mainWindow.getDestination());

		Revised2011Formatter f = null;
		Revised2011Syllabus s = new Revised2011Syllabus();
		int checker = 0;
		try {

			if (mainWindow.getFileName().trim().isEmpty()) {
				// If the user did not specify an output file name...
				s = Revised2011XMLReader.getInstance().readSyllabus(src.getAbsolutePath());
				f = new Revised2011Formatter(s, dest.getAbsolutePath() + "/"
						+ s.getCourseCode() + " " + s.getTerm() + ".pdf");
			} else {
                // If the user specified and output file name...
                s = Revised2011XMLReader.getInstance().readSyllabus(src.getAbsolutePath());
                String filename = mainWindow.getFileName();
           
                
                if(filename.contains("*") || filename.contains("|") || filename.contains("\\") || 
                                filename.contains("/") || filename.contains(":") || filename.contains("\"") ||
                                filename.contains("<") || filename.contains(">") || filename.contains("?")){
                        JOptionPane.showMessageDialog(null, "Wrong filename format!");
                        checker = 0;
                        }
                else
                { 
                	checker = 1;
                }
                
                if(checker == 1){
                	
                f = new Revised2011Formatter(s, dest.getAbsolutePath() + "/"
                                + filename + ".pdf");
                }
        }
			if(checker == 1)
				 mainWindow.displaySuccess("Successfully generated PDF.\nFilename: " + f.outputFileName.substring(dest.getAbsolutePath().length()+1));
			
		} catch (InvalidXMLFileFormatException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			new ErrorFrame("File not found.").show();
			e.printStackTrace();
		} catch (DocumentException e) {
			new ErrorFrame("Document Exception : " + e.getLocalizedMessage())
					.show();
			e.printStackTrace();
		} 
	}

	/**
	 * Generates a preview of the intended output file.
	 */
	public void previewPDF() throws IOException {

		openPDF(mainWindow.getDestination() + "/" + mainWindow.getFileName()
				+ ".pdf");
	}

	/**
	 * Opens the generated or previewed PDF file.
	 * 
	 * @param fileName
	 *            The filename of the file to be opened
	 * @throws IOException
	 */
	public static void openPDF(String fileName) throws IOException {

		File outputFile = new File(fileName);
		Desktop.getDesktop().open(outputFile);
	}

	public void exitProgram() {
		int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?",
				"User Confirmation", JOptionPane.YES_NO_OPTION);
		if(confirm == JOptionPane.YES_OPTION)
				System.exit(0);
	}
	

}
